package com.uuah.server.config.spring.parsers.delegate;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

import com.uuah.server.config.spring.parsers.IUuahDefinitionParser;
import com.uuah.server.util.spring.SpringXMLUtils;
import com.uuah.utils.CollectionUtils;

/**
 * Select sub parser depending on presence of a particular attribute
 */
public class AttributeSelectionDefinitionParser extends
		AbstractParallelDelegatingDefinitionParser {

	private Map attributeToParserIndex = new HashMap();

	public AttributeSelectionDefinitionParser(String attribute,
			IUuahDefinitionParser delegate) {
		super();
		addDelegate(attribute, delegate);
	}

	public void addDelegate(String attribute, IUuahDefinitionParser delegate) {
		addDelegate(delegate);
		attributeToParserIndex.put(attribute, new Integer(size() - 1));
		delegate.setIgnoredDefault(true);
		delegate.removeIgnored(attribute);
	}

	protected IUuahDefinitionParser getDelegate(Element element,
			ParserContext parserContext) {
		NamedNodeMap attributes = element.getAttributes();
		for (int i = 0; i < attributes.getLength(); ++i) {
			String attribute = SpringXMLUtils.attributeName((Attr) attributes
					.item(i));
			if (attributeToParserIndex.containsKey(attribute)) {
				return getDelegate(((Integer) attributeToParserIndex
						.get(attribute)).intValue());
			}
		}
		throw new IllegalArgumentException("Element "
				+ SpringXMLUtils.elementToString(element)
				+ " does not contain any attribute from "
				+ CollectionUtils.toString(attributeToParserIndex.keySet(), 10,
						false));
	}

}